﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;
using StoreClientModule;

namespace MBBStoreClient
{
    public partial class frmDeliverySummaryManager: Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        List<string> itemCode = new List<string>();
        DataTable items = new DataTable();
        DataTable supplier = new DataTable();
        DataTable prods = new DataTable();

        string myDate;
        string[] arrDate;
        string myDay;
        string myMonth;
        string myYear;
        string filter;

        string wrnEntMsg = "";
        float gtotal = 0f;

        bool amtErr = false, supErr = false,
            cmtErr = false;

        //AutoChecker
        Timer tmr = new Timer();
        
        public frmDeliverySummaryManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);

            InitLookUp();
            txtSupplierName.TextChanged += new EventHandler(txtSupplierName_TextChanged);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            States(false);
            //InitializeItemTable();
            txtAmount.TextChanged += new EventHandler(CheckValue);
            btnCommit.Click +=new EventHandler(btnCommit_Click);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            btnPrint.Click +=new EventHandler(btnPrint_Click);
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            myDate = dateFilter.Text;
            arrDate = myDate.Split('/');
            myDay = int.Parse(arrDate[1].Trim()).ToString();
            myMonth = int.Parse(arrDate[0].Trim()).ToString("00");
            myYear = int.Parse(arrDate[2].Trim()).ToString();
            filter = filterCategory.Text;
            t.MethodCall(search);
        }
        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintSummary();
        }
        void btnCommit_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            this.Enabled = false;
            States(false);
            CommitDR();
        }
        void txtSupplierName_TextChanged(object sender, EventArgs e)
        {
            
            DataRow[] dr = supplier.Select("fName='" + txtSupplierName.Text + "'");
            if (dr.Length == 1)
            {
                txtRefNum.Text = dr[0]["fRefNum"].ToString();

                txtSupplierName.ForeColor = Color.Black;
                txtRefNum.ForeColor = Color.Black;
                txtRefNum.ReadOnly = true;
                lblWarning.Text = "";
                supErr = false;
            }
            else //if (txtSupplierName.Text.Length > 0)
            {
                if (!supErr)
                {
                    txtRefNum.Text = "N/A";

                    txtSupplierName.ForeColor = Color.Red;
                    txtRefNum.ForeColor = Color.Red;
                    txtRefNum.ReadOnly = false;
                    lblWarning.Text = "Warning: Supplier not found in the database.\r\nClicking Commit will save the currently entered supplier data.";
                    supErr = true;
                }
            }
            t.MethodCall(CheckEntry);
        }
        
        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":

                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "INIT":
                        proc.DBPUX_Data_Fetch(out dat);
                        //This is to insert initial data to purchaseordergenerate table.
                        
                        supplier = dat[0].ToDataTable();
                        if (!txtSupplierName.Focused)
                        {
                            txtSupplierName.AutoCompleteCustomSource.AddRange(dat[0].ToList<string>(1));
                        }
                        grdItems.DataSource = dat[1].ToDataTable();
                        grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        formatGrid();
                        break;
                    case "SEARCH":
                    case "COMMIT":
                        txtAmount.Text = "";
                        txtInvoice.Text = "";
                        txtSupplierName.Text = "";
                        proc.DBPUX_Data_Fetch(out dat);
                        grdItems.DataSource = dat[0].ToDataTable();
                        grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        grdItems.Columns[4].DefaultCellStyle.Format = "#,#0.00";
                        formatGrid();
                        break;
                    
                };
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch(sender.ToString())
                {
                    case "CheckEntry":
                        if (amtErr)
                            txtAmount.ForeColor = Color.Red;
                        else
                            txtAmount.ForeColor = Color.Black;


                        if (!amtErr && !cmtErr)
                            btnCommit.Visible = true;
                        else
                            btnCommit.Visible = false;

                        //txtTotal.Text = gtotal.ToString("#,#0.00");
                        //btnCommit.Visible = !cmtErr;
                        
                        break;
                    
                }
                tmr.Enabled = true;
            });
        }

        //Operations
        void search()
        {
            string sql = "";
            if (chkMonthly.Checked == false)
            {
                if (filter.Equals("All"))
                {
                    sql = "fDate = '" + dateFilter.Value.ToString("yyyy-MM-dd") + "'";
                }
                else
                {
                    sql = "fDate = '" + dateFilter.Value.ToString("yyyy-MM-dd") + "' AND fCategory = '" + filter + "' ";
                }
            }
            else
            {
                if (filter.Equals("All"))
                {
                    sql = "fDate LIKE '" + myYear + "-" +myMonth+"%'";
                }
                else
                {
                    sql = "fDate LIKE '" + myYear + "-" + myMonth + "%' AND fCategory = '" + filter + "' ";
                }
            }

            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("SEARCH", 4);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fDate AS 'Date', fCategory AS 'Category', fSupplierName AS 'Supplier', fInvoice AS 'Invoice Number', fAmount AS 'Amount', fStamp FROM tbldeliverydetails WHERE "+sql+" ORDER BY fDate ASC, fSupplierName ASC ");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void formatGrid()
        {
            double total = 0.0f;
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                double amt = double.Parse(grdItems.Rows[i].Cells[4].Value.ToString());
                grdItems.Rows[i].Cells[4].Value = double.Parse(grdItems.Rows[i].Cells[4].Value.ToString()).ToString("#,#0.00");
                total += amt;
            }
            txtTotal.Text = total.ToString("#,#0.00");
        }
        void CheckEntry()
        {
            float fAmt = 0f;
            string amt = txtAmount.Text;
            
            //Check Amount
            if (!float.TryParse(amt, out fAmt))
            {
                amtErr = true;
                wrnEntMsg = "Invalid Amount value detected!\r\n";
            }
            else
            {
                amtErr = false;
                wrnEntMsg = "";
            }
        }
        void InitLookUp()
        {
            txtCategory.SelectedIndex = 0;
            filterCategory.SelectedIndex = 0;

            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("INIT", 4);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblsupplierprofile");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fDate AS 'Date', fCategory AS 'Category', fSupplierName AS 'Supplier', fInvoice AS 'Invoice Number', fAmount AS 'Amount', fStamp FROM tbldeliverydetails WHERE fDate = '"+dateFilter.Value.ToString("yyyy-MM-dd")+"'");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void CommitDR()
        {
            //float amt = float.Parse(txtAmount.Text);
            //Construct PO Details.
            UnityScript u = new UnityScript("COMMIT", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tbldeliverydetails(fInvoice, fRefNum, fDate, fCategory, fSupplierName, fAmount)",
                new string[]{
                    txtInvoice.Text,
                    txtRefNum.Text,
                    txtDate.Value.ToString("yyyy-MM-dd"),
                    txtCategory.Text,
                    txtSupplierName.Text,
                    txtAmount.Text
                });
            
            //Transaction Log
            /*u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
                new string[]{
                    StoreClientModule.Common.Username,
                    "Added  worth " + gtotal.ToString("#,#0.00"),
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
             */
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fDate AS 'Date', fCategory AS 'Category', fSupplierName AS 'Supplier', fInvoice AS 'Invoice Number', fAmount AS 'Amount', fStamp FROM tbldeliverydetails WHERE fDate = '" + txtDate.Value.ToString("yyyy-MM-dd") + "'");
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grdItems.Enabled = s;
        }
        
        //Printing Module
        void PrintSummary()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }
        }

        int i = 0;

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 100;
            float lw = e.PageBounds.Width - 100;
            float th = e.PageBounds.Height - 100;
            float tHt = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            //Title
            cFont = new Font("Arial", 16f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(Common.lStoreName, cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString(Common.lStoreAddress, cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 16f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Monthly Report for the Month of " + DateTime.Parse(dateFilter.Text).ToString("MMMM") + " - " + myYear, cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            //e.Graphics.DrawString("Fax Number: (044) 662-37-62", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //Line
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            e.Graphics.DrawString("" + filterCategory.Text, cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            y += tHt;
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));

            y += tHt;
            //Table Columns

            cFont = new Font("Arial", 11f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y += tHt;
            e.Graphics.DrawString("No.", cFont, Brushes.Black, lm + 4, y, new StringFormat());
            e.Graphics.DrawString("Supplier's Name", cFont, Brushes.Black, lm + 50, y, new StringFormat());
            e.Graphics.DrawString("Date", cFont, Brushes.Black, lm + 300, y, new StringFormat());
            e.Graphics.DrawString("Invoice #", cFont, Brushes.Black, lm + 430, y, new StringFormat());
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, lm + 560, y, new StringFormat());

            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lw, y - (tHt / 2)));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 35, y - (tHt / 2)), new PointF(lm + 35, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 290, y - (tHt / 2)), new PointF(lm + 290, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 420, y - (tHt / 2)), new PointF(lm + 420, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 550, y - (tHt / 2)), new PointF(lm + 550, y + tHt));

            //Table

            
            cFont = new Font("Arial Narrow", 11f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            y += (tHt * 1.25f);
            bool nf = false;
            lpp = (lw - y) / tHt;
            int cl = 0;
            

            while (cl <= lpp && i < grdItems.Rows.Count)
            {

                e.Graphics.DrawString((i + 1) + "", cFont, Brushes.Black, lm + 4, y, new StringFormat());
                
                    sf.Alignment = StringAlignment.Near;
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[2].Value.ToString(), cFont, Brushes.Black, lm + 50, y,sf);
                    e.Graphics.DrawString("" + DateTime.Parse(grdItems.Rows[i].Cells[0].Value.ToString()).ToShortDateString(), cFont, Brushes.Black, lm + 300, y, sf);
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[3].Value.ToString(), cFont, Brushes.Black, lm + 430, y, sf);
                    sf.Alignment = StringAlignment.Far;
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[4].Value.ToString(), cFont, Brushes.Black, lw + 2, y, sf);
                

                i++;
                cl++;
            
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 35, y - (tHt / 2)), new PointF(lm + 35, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 290, y - (tHt / 2)), new PointF(lm + 290, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 420, y - (tHt / 2)), new PointF(lm + 420, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 550, y - (tHt / 2)), new PointF(lm + 550, y + tHt));

                y += (tHt * 1.25f);
                
            }
            

            if (i < grdItems.Rows.Count)
            {
                e.HasMorePages = true;

            }
            else
            {
                
                y += (tHt * 1.25f);
                
                sf.Alignment = StringAlignment.Near;
                e.Graphics.DrawString("Total: " , cFont, Brushes.Black, lm + 430, y, sf);
                sf.Alignment = StringAlignment.Far;
                e.Graphics.DrawString("" + txtTotal.Text, cFont, Brushes.Black, lw + 2, y, sf);
                y += (tHt * 1.25f);
                //Nothing Follows
                e.Graphics.DrawString("******************** Nothing Follows ********************", cFont, Brushes.Black, lm + 200, y, new StringFormat());

                e.HasMorePages = false;
                i = 0;
                
            }
        }
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}